package com.coocaa.app.gamecenter.pages.home;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.ScrollView;

import com.coocaa.x.framework.utils.LogUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by luwei on 15-12-25.
 */
public class CustomScrollView extends ScrollView{

    private OnScrollEndListener scrollListener = null;
    private boolean hasSendMsg = false;

    public interface OnScrollEndListener{
        public void scrollEnd();
    }

    public CustomScrollView(Context context) {
        super(context);
    }

    public CustomScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setOnScrollEndListener(OnScrollEndListener listener){
        this.scrollListener = listener;
    }

    public boolean isTop(){
        if (computeVerticalScrollOffset() == 0)
            return true;
        return false;
    }

    public boolean isBottom(){
        if(computeVerticalScrollExtent() + computeVerticalScrollOffset() == computeVerticalScrollRange())
            return true;
        return false;
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (!hasSendMsg) {
            LogUtils.d("scroll", "send check msg");
            handler.sendEmptyMessageDelayed(CHECK_SCROLL, 250);
            hasSendMsg = true;
        }
    }

    private static final int CHECK_SCROLL = 0;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case CHECK_SCROLL:
                    if (isScrollFinish()){
                        LogUtils.d("scroll","scroll is finish");
                        if (scrollListener != null)
                            scrollListener.scrollEnd();
                        hasSendMsg = false;
                    }else{
                        handler.sendEmptyMessageDelayed(CHECK_SCROLL,50);
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private boolean isScrollFinish(){
        try {
            Field mScrollCacheField = ScrollView.class.getDeclaredField("mScroller");
            mScrollCacheField.setAccessible(true);
            Object mScroller = mScrollCacheField.get(this); // scr is your Scroll View
            Method method = mScroller.getClass().getDeclaredMethod("isFinished");
            method.setAccessible(true);
            return (Boolean)method.invoke(mScroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
